<template>
  <div class="channel-edit">
    <van-cell title="我的频道" :border="false">
      <van-button color="red" class="edit-btn" size="small" round plain type="primary" @click="isEdit = !isEdit">
        {{ isEdit ? '完成' : '编辑' }}
      </van-button>
    </van-cell>
    <van-grid :gutter="10" class="my-grid" :border="false">
      <van-grid-item
        :class="{ active: index === active }"
        :icon="isEdit && index !== 0 ? 'close' : ''"
        :text="item.name"
        v-for="(item, index) in channels"
        :key="item.id"
        @click="onMyClick(index, item.id)"
      />
    </van-grid>

    <van-cell title="推荐频道" :border="false">
    </van-cell>
    <van-grid icon-size="0.5rem" :gutter="10" direction="horizontal" class="my-grid" :border="false">
      <van-grid-item
      @click="onRecommendChannel(item)"
        v-for="item in recommendChannels"
        :key="item.id"
        icon="plus"
        :text="item.name"
      />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannel } from '@/api/article.js'
import { Toast } from 'vant'
import { mapState } from 'vuex'
import { setStorage } from '@/utils/storage.js'
import { addUserChannelItem, removeUserChannelItem } from '@/api/user.js'
export default {
  props: {
    channels: {
      type: Array,
      required: true
    },
    // 索引高亮显示
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      isEdit: false,
      allChannels: []
    }
  },

  created () {
    this.loadAllChannel()
  },

  computed: {
    ...mapState(['user']),
    // 推荐频道
    recommendChannels () {
      // 用数组方法filter 对allChannels进行筛选
      // allChannels的每一项 是否在channels里，如果没有在channels里，那就属于recommendChannels
      const arr = this.allChannels.filter(item => { // 筛选
        const flag = this.channels.some(item2 => { // 符合条件 会return出true 反之则false
          return item2.id === item.id // 不能用item2 === item ,这样会一直返回false，复杂数据类型比的是地址
        })
        return !flag
      })
      return arr
    }

    // 代码简化
    // recommendChannels () {
    //   return this.allChannels.filter(item => {
    //     return !this.channels.some(item2 => item2.id === item.id)
    //   })
    // }
  },

  methods: {
    // 点击了我的频道
    onMyClick (index, id) {
      if (this.isEdit) {
        // 处于编辑状态
        if (index === 0) return
        if (index <= this.active) {
          // this.active-- // 子组件不能为父组件的数据赋值，这个操作涉及到赋值，所以不能这样做
          this.$emit('set-active') // 传到父组件进行操作 this.active--
        }
        this.channels.splice(index, 1)
        // 删除持久化
        this.deleteChannelStorage(id)
      } else {
        // 处于非编辑状态
        this.$emit('on-go', index)
      }
    },
    // 删除持久化
    async deleteChannelStorage (id) {
      // 未登录
      console.log('未登录删除持久化')
      if (!this.user) return setStorage('MY-CHANNELS', this.channels)
      // 已登录
      Toast.loading({
        message: '删除中...',
        forbidClick: true,
        duration: 0 // 持续提示toast
      })
      try {
        await removeUserChannelItem(id)
        Toast.success('删除成功')
      } catch (err) {
        Toast.fail('删除失败')
      }
    },
    // 加载所有频道
    async loadAllChannel () {
      try {
        const res = await getAllChannel()
        this.allChannels = res.channels
      } catch (err) {
        Toast('获取频道列表失败')
      }
    },
    // 点击了推荐频道
    async onRecommendChannel (obj) {
      // 只是操作了页面的显示
      this.channels.push(obj)

      Toast.loading({
        message: '添加中...',
        forbidClick: true,
        duration: 0 // 持续提示toast
      })

      // 进行数据持久化
      if (this.user) {
        // 登录
        try {
          await addUserChannelItem({
            id: obj.id,
            seq: this.channels.length
          })
          Toast.success('添加成功')
        } catch (err) {
          Toast.fail('添加失败')
        }
      } else {
        setStorage('MY-CHANNELS', this.channels)
        Toast.success('添加成功')
      }
    }
  }
}
</script>

<style scoped lang='less'>
.channel-edit {
  .edit-btn {
    width: 104px;
    height: 48px;
  }

  /deep/.my-grid {
    .van-grid-item {
      width: 160px;
      height: 86px;
      border-radius: 6px;
    }
    .van-grid-item__content {
      background-color: #f4f5f6;
    }

    .van-icon-close {
      font-size: 35px;
      position: absolute;
      top: -10.5px;
      right: 5px;
    }
    .van-grid-item__icon+.van-grid-item__text {
      margin-top: 0;
    }

    .active {
      .van-grid-item__text {
        color: red;
      }
    }
  }
}
</style>
